package com.stx.jeepay.manager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.stx.jeepay.core.entity.SysEntitlementEntity;
import com.stx.jeepay.core.entity.SysUserEntity;
import com.stx.jeepay.core.enums.CS;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.model.security.JeeUserDetails;
import com.stx.jeepay.core.service.SysEntitlementService;
import com.stx.jeepay.core.utils.TreeDataBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Api(tags = "登录者信息")
@RestController
@RequestMapping("api/current")
public class CurrentUserController extends CommonCtrl {

    @Autowired
    private SysEntitlementService sysEntitlementService;

    @ApiOperation("查询当前登录者的用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header")
    })
    @GetMapping("/user")
    public ApiRes currentUserInfo(){
        // 获取当前用户信息
        JeeUserDetails jeeUserDetails = getCurrentUser();
        SysUserEntity sysUser = jeeUserDetails.getSysUser();

        //1. 当前用户所有权限ID集合
        List<String> entIdList = new ArrayList<>();
        jeeUserDetails.getAuthorities().stream().forEach(i-> entIdList.add(i.getAuthority()));

        List<SysEntitlementEntity> allMenuList = new ArrayList<>();    //所有菜单集合

        //2. 查询出用户所有菜单集合 (包含左侧显示菜单 和 其他类型菜单 )
        if (!entIdList.isEmpty()){
            allMenuList = sysEntitlementService.list(new LambdaQueryWrapper<SysEntitlementEntity>()
                    .in(SysEntitlementEntity::getEntId,entIdList)
                    .in(SysEntitlementEntity::getEntType, Arrays.asList(CS.ENT_TYPE.MENU_LEFT,CS.ENT_TYPE.MENU_OTHER))
                    .eq(SysEntitlementEntity::getSysType,CS.SYS_TYPE.MGR)
                    .eq(SysEntitlementEntity::getState,CS.PUB_USABLE));
        }
        //4. 转换为json树状结构
        JSONArray jsonArray = (JSONArray) JSON.toJSON(allMenuList);
        List<JSONObject> allMenuRouteTree = new TreeDataBuilder(jsonArray,
                "entId", "pid", "children", "entSort", true)
                .buildTreeObject();
        //1. 所有权限ID集合
        sysUser.addExt("entIdList", entIdList);
        sysUser.addExt("allMenuRouteTree", allMenuRouteTree);
        return ApiRes.ok(getCurrentUser().getSysUser());
    }
}
